package com.yixing.tech.common.config;

import org.bson.Document;
import org.bson.types.ObjectId;
import org.springframework.core.convert.converter.Converter;
import org.springframework.data.convert.ReadingConverter;

import java.util.List;

/**
 * @author yixing tech
 */
@ReadingConverter
public class DocumentToDocumentConverter implements Converter<Document, Document> {

    @Override
    public Document convert(Document document) {
        _id2Id(document);
        return document;
    }


    private void _id2Id(Document map) {
        Object _id = map.get("_id");
        if (_id instanceof ObjectId) {
            map.remove("_id");
            map.put("id", _id.toString());
        }

        Object id = map.get("id");
        if (id instanceof ObjectId) {
            map.put("id", id.toString());
        }
        map.values().forEach(m -> {
            if (m instanceof Document) {
                _id2Id((Document) m);
            } else if (m instanceof List) {
                List ja = (List) m;
                ja.forEach(n -> {
                    if (n instanceof Document) {
                        _id2Id((Document) n);
                    }
                });
            }
        });
    }
}

